package com.maishi.programmer.jainzhioffer;

/**
 * Created by brossdong on 2018/4/16.
 * 翻转单词顺序列
 * student. a am I ==> I am a student.
 */
public class TestProblem58 {

    public String ReverseSentence(String str) {

        if (str.length() < 2|| str == null) return "";
        char[] array = str.toCharArray();
        reverse(array,0,str.length() - 1);
        System.out.println(array);
        int start = 0;//记录每个单词的起始位置
        int end = 0;//单词的终止位置
        while (end < array.length) {
            //最后一个单词无空格
            if (array[end] != ' ') {
                if (end == array.length - 1) {
                    reverse(array,start,end);
                    System.out.println(array);
                }
                end++;
            }
            //当遇到空格时，把空格之前的单词翻转，并且把start置为end
            else if (array[end] == ' ') {
                reverse(array,start,end-1);
                end++;
                start = end;//下一个单词的起始位置
            }
        }
        return String.valueOf(array);
    }

    public void reverse (char[] array,int start,int end) {
        char temp = ' ';
        while (start < end) {
            temp = array[start];
            array[start++] = array[end];
            array[end--] = temp;
        }
    }


    public static void main(String[] args) {
        TestProblem58 t = new TestProblem58();
        String str = t.ReverseSentence("I am a student.");
        System.out.println(str);
    }

}
